package me.firstapp.bts.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.bts.service.AccountJobService;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.module.weixin.jinbi.JinBiAccountTrace;
import me.firstapp.module.weixin.weibi.WeiBiAccount;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace;
import me.firstapp.module.weixin.weibi.WeiBiAccountTrace.ChangeType;
import me.firstapp.service.weixin.account.WeiBiAccountService;
import me.firstapp.service.weixin.account.WeiBiAccountTraceService;

@Service
public class AccountJobServiceImpl implements AccountJobService {

	private static Logger logger = LoggerFactory.getLogger(AccountJobServiceImpl.class);

	@Autowired
	private WeiBiAccountService weiBiAccountService;

	@Autowired
	private WeiBiAccountTraceService weiBiAccountTraceService;

	@Override
	public void settleWeiBiToJinBi() {
		logger.info("积分兑换贝币开始...");
		long start = System.currentTimeMillis();
		for (int pageNo = 1; pageNo < 1000000; pageNo++) {
			List<WeiBiAccount> weiBiAccounts = weiBiAccountService.findWeiBiAccounts(pageNo, 100);
			if (null == weiBiAccounts || weiBiAccounts.isEmpty()) {
				break;
			}
			logger.info("待兑换的积分账户数量为：" + weiBiAccounts.size());
			for (WeiBiAccount weiBiAccount : weiBiAccounts) {
				logger.info("卡号【" + weiBiAccount.getCardNo() + "】积分账户开始兑换贝币...");
				WeiBiAccountTrace weiBiAccountTrace = weiBiAccountTraceService
						.findByWeiBiAccountIdAndChangeTypeAndChangeDate(weiBiAccount.getId(),
								ChangeType.JINBI_SUB_WEIBI, Integer.valueOf(DateUtils
										.getDateStr(DateUtils.getBeforeOrNextDay(new Date(), -1), "yyyyMMdd")));
				if (null == weiBiAccountTrace) {
					JinBiAccountTrace jinBiAccountTrace = weiBiAccountService.executeExchangeJinBi(weiBiAccount);
					logger.info("卡号【" + weiBiAccount.getCardNo() + "】积分账户兑换贝币成功，兑换金额："
							+ jinBiAccountTrace.getChangeValue() + "贝币。");
					// JinBiAccountTrace jinBiAccountTrace =
					// weiBiAccountService.executeExchangeJinBi(weiBiAccount);
					// if (null != jinBiAccountTrace) {
					// // try {
					// // // 调用发送模板消息接口，通知用户贝币变动
					// // OpenApiUtils.sendJinBiChangeMessage(restTemplate,
					// // jinBiAccountTrace.getId());
					// // } catch (Exception e) {
					// // e.printStackTrace();
					// // logger.error("调用sendJinBiChangeMessage.do接口失败", e);
					// // }
					// }
				}
				logger.info("卡号【" + weiBiAccount.getCardNo() + "】积分账户兑换贝币结束...");
			}
		}
		logger.info("积分兑换金币结束...耗时：" + (System.currentTimeMillis() - start));
	}

}
